import { FC, useEffect, useRef, useState } from 'react';
import './index.less';
import { DownloadOutlined } from '@ant-design/icons';
import { Button, Checkbox, Input, message, Select } from 'antd';
import { getRunDataBack, getRunDataProcess } from '@/api/run-data';

import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import { commonOption, optionsChecked, optionsNotCheck } from './constant';
import { getGlobalConfig } from '@/api/config';

const { Option } = Select;
const HistoryData: FC = () => {
  const [type, setType] = useState<string>('layerId');
  const [lineName, setLineName] = useState<string>('');

  const [station, setStation] = useState<Array<string>>([]);
  const [stationOption, setStationOption] = useState<Array<any>>(optionsChecked);

  const [failListVal, setFailListVal] = useState<Array<{ station: string; message: string }>>([]);
  const [content, setContent] = useState<string>('');

  const [title, setTitle] = useState<string>('');

  const [loading, setLoading] = useState<boolean>(false);
  const [show, setShow] = useState<boolean>(false);
  const [linePmp, setLinePmp] = useState<Array<any>>([]);

  useEffect(() => {
    initRequest();
  }, []);

  //  请求config拿到这个页面是否显示+前制程产线的名称
  const initRequest = async () => {
    try {
      const resBack = await getGlobalConfig();
      if (resBack.code == 200 && resBack.data) {
        if (resBack?.data.hasOwnProperty('runDataPage')) {
          const pmpLineList = resBack.data.runDataPage.pmpLine;
          const showStatus = resBack.data.runDataPage.show;
          if (showStatus == 'open') {
            setShow(true);
            setLinePmp(pmpLineList);
            setLineName(pmpLineList[0]);
          } else {
            setShow(false);
          }
        }
      }
    } catch (error) {
      console.log('run dataPage', error);
    }
  };

  // 选中工站
  const handleChange = val => {
    setStation(val);
  };

  /**
   * 开始启动的按钮
   * @returns
   */
  const startRunData = async () => {
    if (!type) return message.warning('跑数据的类型不能为空!');
    if (!content) return message.warning('内容不能为空!');
    if (!station || !station?.length) return message.warning('站点不能为空!');
    if (type == 'layerId' && !lineName) {
      return message.warning('跑前制程的数据，产线不能为空!');
    }
    setFailListVal([]); //置为空
    setTitle(type + ':' + content); //置为空
    const params = {
      type: type,
      content: content,
      station: station,
      lineName: lineName
    };
    console.log('启动跑数据---参数；', params);
    setLoading(true);
    try {
      const backData = await getRunDataBack(params);
      console.log('后端的返回结果:', backData);
      if (backData?.code == 200) {
        loopGetTaskProcess(false, 1, 75, 4000); //15一分钟
      } else {
        setLoading(false);
      }
    } catch (error) {
      console.log('axios-error--getRunDataBack=', error);
      setLoading(false);
    }
  };

  /**
   * 轮询获取任务的进程
   */
  const loopGetTaskProcess = (code: boolean, num: number, maxLen: number, interval: number) => {
    console.log('次数：', num, '状态：', code);
    if (code) return;
    if (num >= maxLen) {
      console.log('轮询达到最大次数：还没有拿到最后的结果，怎么办', maxLen);
      setLoading(false);
      message.warning('轮询获取任务的进程,次数已经超过最大数量,任务还没完成！请开发人员排查原因！最大数量是:' + maxLen);
      return;
    }
    setTimeout(async () => {
      try {
        const runProcess = await getRunDataProcess();
        if (runProcess && runProcess?.isEnd) {
          console.log('任务结束，不用再次请求,本次请求的结果是：', runProcess);
          code = true;
          setLoading(false);
          if (runProcess?.status == 'sucess') {
            message.warning('本次跑数据结束了，结束了，哈哈哈哈');
          } else {
            if (runProcess?.failList.length) {
              setFailListVal(runProcess?.failList);
            }
          }
        } else {
          loopGetTaskProcess(code, num, maxLen, interval);
        }
        num = num + 1;
      } catch (error) {
        console.log('axios-error--getRunDataProcess=', error);
        setLoading(false);
      }
    }, interval);
  };

  //  控制工站的全选&&取消全选
  const onChange = (e: CheckboxChangeEvent) => {
    console.log(`checked = ${e.target.checked}`);
    if (e.target.checked) {
      if (type == 'lotId') {
        setStation(commonOption.map(v => v.value));
      } else {
        setStation(stationOption.map(v => v.value));
      }
    } else {
      setStation([]);
    }
  };

  // 选中跑数据的类型类型
  const checkType = (val: string) => {
    setType(val);
    console.log('===', val);
    if (val == 'lotId') {
      // 前制程的工站抽取数据；
      setStationOption(optionsNotCheck);
    } else {
      setStationOption(optionsChecked);
    }
  };

  return (
    <>
      {show ? (
        <div className="history-data">
          <div className="content">
            <div className="title"> 跑数据</div>
            <div className="line-one">
              <div className="lable">跑数据的类型：</div>
              <Select value={type} onSelect={checkType} style={{ width: 100 }}>
                <Option key={'layerId'} value="layerId">
                  layerId
                </Option>
                <Option key={'lotId'} value="lotId">
                  lotId
                </Option>
              </Select>
              <div className="lable"> 前制程产线名称：</div>
              <Select value={lineName} onSelect={(val: string) => setLineName(val)} style={{ width: 70 }}>
                {linePmp.map((item: string, index) => (
                  <Option key={item + index} value={item}>
                    {item}
                  </Option>
                ))}
                {/* <Option key={'A'} value="A线">
                  A线
                </Option>
                <Option key={'B'} value="B线">
                  B线
                </Option> */}
              </Select>
              <div className="lable">内容:</div>
              <div className="lable">
                <Input
                  className="input-content"
                  value={content}
                  onChange={val => {
                    setContent(val.target.value);
                  }}
                ></Input>
              </div>
              <div className="lable">跑数据的站点：</div>
              <div>
                <Checkbox onChange={onChange}>全选</Checkbox>
              </div>
              <div>
                {/* defaultValue={['slit']} */}
                <Select mode="multiple" allowClear style={{ width: 400 }} value={station} onChange={handleChange} options={stationOption} />
              </div>

              <Button loading={loading} type="primary" onClick={startRunData} style={{ marginLeft: '20px', width: '160px' }}>
                开始启动
              </Button>
            </div>

            <div className="error-content">
              {title}
              本次失败工站总数：{failListVal.length ? failListVal.length : 0}
              {failListVal.map((item: { station: string; message: string }, index: number) => (
                <div key={index}>
                  <div>
                    [{index + 1}]：工站：{item.station}
                  </div>
                  <div>报错内容：{item.message}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      ) : (
        ''
      )}
    </>
  );
};
export default HistoryData;
